<?php
require_once('common.php');
require_once('tests.php');

class lesson extends common {
	var $tbl = 'lessons';
	var $f = array();
	var	$parent,
			$children,
			$next, $prev,
			$active;
	
	function __construct($param=NULL) {
		parent::__construct();
		global $db;
		if (is_null($param)) :
			return true;
		elseif(is_array($param)) :
			$this->f = $param;
		elseif(is_string($param) || is_int($param)) :
			$where = "";
			if (is_string($param)) :
				$param = block($param);
				$where = " WHERE slug='$param' LIMIT 1";
			elseif (is_int($param)) :
				$where = " WHERE id='$param' LIMIT 1";
			endif;
			$sql = "
				SELECT
					 id, parent_id, title, text, duration, slug, `order`
				FROM
					$this->tbl
				$where";
				
			$this->f = $db->query_line($sql);

		endif;
		if (empty($this->f)) :
			$this->event('lesson_not_found',"No se encuentra el tema '$param'");
		endif;
	}
	
	function get_parent($force=false) {
		$return = false;
		if (!empty($this->f["parent_id"]) && (empty($this->parent) || $force)) :
			$this->parent = new lesson((int) $this->f["parent_id"]);
			$return = $this->parent->id();
		elseif (!empty($this->parent)) :
			$return = $this->parent->id();
		endif;
		return $return;
	}
	
	function get_parent_root($force=false){
		$return = &$this;
		if ($this->get_parent($force)){
			$return = &$this->parent->get_parent_root($force);
		}
		return $return;
	}
	
	function get_result($conditions){
		$tests = new tests();
		$return = false;
		$conditions['lesson_id'] = $this->id();
		$result = $tests->get_results($conditions,1);
		if (!empty($result) && is_array($result)){
			$result = array_shift($result);
			$return = $result['result'];
		}
		return $return;
	}
	
	function create_body() {
		return $this->f;
	}
	function update_body($no_update_fields=array()) {
		return array_diff_assoc($this->f,$no_update_fields);
	}
	function delete_body() {
		return true;
	}

	function next(){
		$return = false;
		if (is_object($this->children) && $this->children->count()){
			$return = $this->children->first();
		}elseif ($this->next){
			$return = &$this->next;
		}elseif ($this->parent){
//			unset($this->parent->children);
			$return = &$this->parent->next;
		}
		return $return;
	}

	function prev(){
		$return = false;
		if ($this->prev && is_object($this->prev->children) && $this->prev->children->count()){
			$return = $this->prev->children->last();
		}elseif ($this->prev){
			$return = &$this->prev;
		}elseif ($this->get_parent()){
			$return = &$this->parent; 
		}
		return $return;
	}

	function url($echo=true){
		$return = url."lesson/".urlencode($this->slug())."/";
		if ($echo){
			echo $return;
		}
		return $return;
	}
}
?>